import datetime
import hashlib
import hmac
import json
import time
from datetime import datetime, timezone
from hashlib import sha256
import binascii
import requests
from retrying import retry
import chardet
class Utils(object):

    # test环境/预发布环境 云游戏AK/SK
    # 租户: Cloudgame
    # AK = "l0lsgFT8ZrZ5Gqys"
    # SK = "qAfbUn1dEMDQTxJf"

    # 生产环境 云游戏AK/SK
    # 租户: Cloudgame
    AK = "oi3y389zUjlojMjz"
    SK = "HZESYV4sEz50jGyp"

    # 生产环境 云游戏AK/SK
    # 租户: testCloudgame
    # AK = "P51NPW8cwsJAEEz4"
    # SK = "TOud21U8pE4Mpq00"

    httpRequestMethod = "POST"
    # 测试环境
    # url = 'http://iaas-api-test.icloudsky.com/api/v1'
    # 预发布环境
    # url = 'https://iaas-api-pre.icloudsky.com/api/v1'
    # 生产
    url = 'http://iaas-api.icloudsky.com/api/v1'

    @staticmethod
    def genere_timestamp():
        TS = time.time()
        str_TS = str(TS)
        return str_TS[0:10]

    @staticmethod
    def get_sign(action, payload):
        now = datetime.now(timezone.utc)
        payload_str = json.dumps(payload)
        hash_value = Utils.sha256_hash(payload_str)
        canonicalRequest = Utils.httpRequestMethod + "\n" + action + "\n" + hash_value
        hashedCanonicalRequest = Utils.sha256_hash(canonicalRequest)
        Date = now.strftime('%Y-%m-%d')
        string2sign = Utils.genere_timestamp() + "\n" + Date + "/yt_request" + "\n" + hashedCanonicalRequest
        SecretDate = Utils.hmac_sha256(Date, ("YT" + Utils.SK).encode('utf-8'))
        SecretSigning = Utils.hmac_sha256("yt_request", SecretDate)
        signature = Utils.hmac_sha256(string2sign, SecretSigning)
        signature_end = Utils.hex_encode_to_string(signature)
        return signature_end

    @staticmethod
    def sha256_hash(message):
        sha256 = hashlib.sha256()
        sha256.update(message.encode('utf-8'))
        hash_value = sha256.hexdigest()
        return hash_value

    @staticmethod
    def hmac_sha256(s, key):
        s = s.encode('utf-8')
        sign = hmac.new(key, s, digestmod=sha256).digest()
        return sign

    @staticmethod
    def hex_encode_to_string(byte_string):
        return binascii.hexlify(byte_string).decode('utf-8')

    @retry(stop_max_attempt_number=30, wait_fixed=2000)
    def get_result(self, action, payload):
        time_stamp = Utils.genere_timestamp()
        headers = {'X-ICS-Action': action, 'X-ICS-AK': self.AK, 'X-ICS-TimeStamp': time_stamp,
                   'Content-Type': 'application/json',
                   'X-ICS-Sign': Utils.get_sign(action, payload), 'X-ICS-TraceID': "flow_" + time_stamp}
        response = requests.post(Utils.url, data=json.dumps(payload), headers=headers)
        if response.status_code != 200:
            raise Exception('返回状态码不对')
        # 使用chardet检测编码
        detected_encoding = chardet.detect(response.content)['encoding']
        response.encoding = detected_encoding
        print(json.dumps(response.json(), indent=4))
        return response.json()